<!--
 * @Author: MarioGo
 * @Date: 2021-11-11 10:22:47
 * @LastEditTime: 2021-11-11 10:22:47
 * @LastEditors: MarioGo
 * @Description: 文件描述
 * @FilePath: /zheye/src/components/Message.vue
 * 可以输入预定的版权声明、个性签名、空行等
-->
<template>
  <teleport to="#message">
    <div
      class="alert message-info fixed-top w-50 mx-auto d-flex justify-content-between mt-2"
      :class="classObject"
      v-if="isVisible"
    >
      <span>{{ message }}</span>
      <button type="button" class="btn-close" aria-label="Close" @click.prevent="hide"></button>
    </div>
  </teleport>
</template>

<script lang="ts">
import { defineComponent, PropType, ref } from 'vue';
import useDOMCreate from '../hooks/useDOMCreate';

export type MessageType = 'success' | 'error' | 'default';
export default defineComponent({
  name: 'Message',
  props: {
    message: String,
    type: {
      type: String as PropType<MessageType>,
      default: 'default',
    },
  },
  emits: ['close-message'],
  setup(props, context) {
    // 创建teleport组件挂载的节点
    useDOMCreate('message');
    const isVisible = ref(true);
    const classObject = {
      'alert-success': props.type === 'success',
      'alert-danger': props.type === 'error',
      'alert-primary': props.type === 'default',
    };
    // 点击x按钮关闭消息窗口
    const hide = () => {
      isVisible.value = false;
      context.emit('close-message', true);
    };
    return {
      classObject,
      isVisible,
      hide,
    };
  },
});
</script>
